<?php

namespace App\Listeners;

use App\Events\CourseDistribution;
use App\User;
use App\UserBalanceRecord;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleCourseDistribution
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CourseDistribution  $event
     * @return void
     */
    public function handle(CourseDistribution $event)
    {
        $order = $event->order;
        $user = User::find($order->user_id);
        $course = $order->courseable;

        if ($user && $user->parent_id != 0 && $course) {
            $pUser = User::find($user->parent_id);
            if ($pUser) {
                // 一级提成
                if ($course->bonus_ratio_1 > 0) {
                    $bonus = floatval($course->price * $course->bonus_ratio_1);
                    $pUser->balance = $pUser->balance + $bonus;
                    $pUser->save();
                    // 记录
                    UserBalanceRecord::create([
                        'user_id' => $pUser->id,
                        'type' => 1,
                        'type_desc' => 'DISTRIBUTION',
                        'status' => 1,
                        'amount' => $bonus,
                        'trade_no' => $order->order_sn,
                        'comment' => "用户{$user->name}购买课程，获得分销提成"
                    ]);
                }
                // 二级提成
                $ppUser = User::find($pUser->parent_id);
                if ($ppUser) {
                    // 一级提成
                    if ($course->bonus_ratio_2 > 0) {
                        $bonus = floatval($course->price * $course->bonus_ratio_2);
                        $ppUser->balance = $ppUser->balance + $bonus;
                        $ppUser->save();
                        // 记录
                        UserBalanceRecord::create([
                            'user_id' => $ppUser->id,
                            'type' => 1,
                            'type_desc' => 'DISTRIBUTION',
                            'status' => 1,
                            'amount' => $bonus,
                            'trade_no' => $order->order_sn,
                            'comment' => "用户{$user->name}购买课程，获得分销提成"
                        ]);
                    }
                }
            }
        }
    }
}
